#pragma once

#include <iostream>
#include <string>
#include <fstream>
#include <unordered_map>
#include "Log.hpp"
#include "Common.hpp"

using namespace LogModule;

const std::string gpath = "./";
const std::string gfilename = "dict.txt";
const std::string gsep = ": ";

class Dictionary
{
    bool LoadDictionary()
    {
        std::string file = _path + _filename;
        std::ifstream in(file); // 默认打开以只读打开
        if (!in.is_open())
        {
            LOG(LogLevel::FATAL) << "open file " << file << "error";
            return false;
        }
        std::string line;
        while (std::getline(in, line))  // getline重载了operator bool
        {
            std::string key;
            std::string value;
            if (SplitString(line, &key, &value, gsep))
            {
                _dictionary.insert(std::make_pair(key, value));
            }
        }
        in.close();
        return true;
    }
public:
    Dictionary(const std::string& path = gpath, const std::string& filename = gfilename)
    :_path(path)
    ,_filename(filename)
    {
        LoadDictionary();
        // Print();
    }

    std::string Translate(const std::string& word)
    {
        auto iter = _dictionary.find(word);
        if (iter == _dictionary.end()) return "None";
        return iter->second;
    }

    void Print()
    {
        for (const auto& iter : _dictionary)
        {
            std::cout << iter.first << ":" << iter.second << std::endl;
        }
    }

    ~Dictionary()
    {}
private:
    std::unordered_map<std::string, std::string> _dictionary;
    std::string _path;
    std::string _filename;
};